package com.ccl.iot.managers;

import android.content.Context;
import android.os.PowerManager;
import android.util.Log;

import com.ccl.iot.App;
import com.ccl.iot.EIOT_RESULT;
import com.ccl.iot.IOTDataType.IOTLong;
import com.ccl.iot.IOTNetAPI;
import com.ccl.iot.IOTNetAPIConst;
import com.ccl.iot.IOTObject.IOTScannableObject;
import com.ccl.iot.IOTScanner;
import com.ccl.iot.SequenceInvokeList;
import com.ccl.iot.asynctask.SendIrTask;
import com.ccl.iot.batch.BatchDBManager;
import com.ccl.iot.batch.IOTBatch;
import com.ccl.iot.batch.IOTBatchInterface;
import com.ccl.iot.bean.BatchBean;
import com.ccl.iot.bean.CodeviewBean;
import com.ccl.iot.bean.IOTBatchItemInfoBean;
import com.ccl.iot.bean.IrToBatchItemBean;
import com.ccl.iot.device.BatchIntentionDevice;
import com.ccl.iot.device.IOTBLDNADevice;
import com.ccl.iot.dvr.utils.Consts;
import com.ccl.iot.dvr.utils.LoggerUtil;
import com.ccl.iot.ir.DBUtils;
import com.ccl.iot.monitor.ScreenMonitor;
import com.ccl.iot.object.IOTBatchInfo;
import com.ccl.iot.object.IOTBatchItemInfo;
import com.ccl.iot.privates.ListMap;
import com.ccl.iot.publics.Debugger;
import com.ccl.iot.publics.NetInfo;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.mysql.jdbc.Connection;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import static android.os.PowerManager.PARTIAL_WAKE_LOCK;

public class BatchManager extends ListedManager<IOTBatch> implements IOTScannableObject<IOTBatch> {
    /*
     * 	Static functions
     */
    private static BatchManager gDefault = null;

    private static final String INVALID_TASK_NAME = "invalid_task.txt";

    public static BatchManager GetDefaultManager(Context aContext) {
        if (gDefault == null) {
            gDefault = new BatchManager(aContext);
        }

        return gDefault;
    }

    public static BatchManager GetDefaultManager() {
        return gDefault;
    }

    public static long Encode(IOTBatch aBatch) {
        if (aBatch != null) {
            return aBatch.getID();
        }
        return 0;
    }

    public static IOTBatch Decode(long aBatch) {
        IOTBatch tBatch = null;
        if (aBatch != 0) {
            if (gDefault != null) {
                tBatch = gDefault.findBatch(aBatch);

                if (tBatch == null) {
                    if (gDefault.startScan(null)) {
                        tBatch = gDefault.findBatch(aBatch);
                    }
                }
            }
        }
        return tBatch;
    }

    public static boolean Execute(long aBatch) {
        if (gDefault != null) {
            return gDefault.executeBatch(aBatch);
        }

        return false;
    }

    /*
     * 	Non-static functions
     */
    private IOTNetAPI iNetAPI = null;
    private UserManager iUserManager = null;
    private PowerManager.WakeLock iWakeLock = null;

    private ListMap<Long, IOTBatch> iBatchs = null;

    private long mTmpVersion = 0;
    private long mLastVersion = 0;

    private BatchManager(Context aContext) {
        super(aContext);

        if (aContext != null) {
            PowerManager tManager = (PowerManager) aContext.getSystemService(Context.POWER_SERVICE);

            if (tManager != null) {
                iWakeLock = tManager.newWakeLock(PARTIAL_WAKE_LOCK, this.getClass().getName());
            }
        }

        iNetAPI = IOTNetAPI.GetInstance();
        iUserManager = UserManager.GetDefaultManager();

        iUserManager.addUserEventListener(iUserLoginListener);
        onCreate();
    }

    @Override
    public boolean filteError(int aError) {
        if (aError == EIOT_RESULT.EIOT_RESULT_GENERAL_NO_BATCH ||
                aError == EIOT_RESULT.EIOT_RESULT_GENERAL_BATCH_NO_ITEM) {
            return true;
        }
        return false;
    }

    private void onCreate() {
        super.create();
    }

    @Override
    public void onSuspend() {
        super.onSuspend();

        iExecuteList.clear();
        //iBatchScanner.stopScan();
    }

    private UserManager.UserEventListener iUserLoginListener = new UserManager.UserEventListener() {
        @Override
        public void onLoginEvent(boolean aCanceled) {

        }

        @Override
        public void onPrepareLogout() {
        }

        @Override
        public void onLogout(boolean aOK) {
            //                        startScan(null);
        }
    };

    public ArrayList<IOTBatch> getList() {
        final ListMap<Long, IOTBatch> tBatchs = iBatchs;

        if (tBatchs != null && tBatchs.size() > 0) {
            ArrayList<IOTBatch> tList = new ArrayList<IOTBatch>();

            synchronized (tBatchs) {
                tList.addAll(tBatchs.getValues());
            }

            if (tList.size() > 0) {
                return tList;
            }
        }

        return null;
    }

    public IOTBatch findBatch(Object aID) {
        final ListMap<Long, IOTBatch> tBatchs = iBatchs;

        if (aID != null && tBatchs != null) {
            synchronized (tBatchs) {
                if (aID instanceof Long) {
                    return tBatchs.getValue((Long) aID);
                } else if (aID instanceof String) {
                    String tName = (String) aID;
                    IOTBatch tBatch;

                    for (int i = 0; i < tBatchs.size(); i++) {
                        if ((tBatch = tBatchs.getValueAt(i)) != null) {
                            if (tBatch.getName().equals(tName)) {
                                return tBatch;
                            }
                        }
                    }
                }
            }
        }

        return null;
    }

    public int findBatchIndex(IOTBatch aBatch) {
        final ListMap<Long, IOTBatch> tBatchs = iBatchs;

        if (aBatch != null && tBatchs != null) {
            synchronized (tBatchs) {
                return tBatchs.indexOfValue(aBatch);
            }
        }

        return -1;
    }

    public ArrayList<IOTBatch> findSimilarBatch(ArrayList<IOTBatchItemInfo> aItems) {
        final ListMap<Long, IOTBatch> tOldBatchs = iBatchs;

        if (aItems != null && tOldBatchs != null) {
            synchronized (tOldBatchs) {
                int tCount = tOldBatchs.size();

                if (tCount > 0) {
                    IOTBatch tBatch;
                    ArrayList<IOTBatch> tBatchs = new ArrayList<IOTBatch>();
                    IOTBatchItemInfo tBatchItem1;
                    IOTBatchItemInfo tBatchItem2;
                    ArrayList<IOTBatchItemInfo> tBatchItems;

                    for (int i = tCount - 1; i >= 0; i--) {
                        if ((tBatch = tOldBatchs.getValueAt(i)) != null) {
                            if ((tBatchItems = getAllBatchItemInfo(tBatch.getID())) != null) {
                                if (aItems.size() == tBatchItems.size()) {
                                    boolean tSame = true;

                                    for (int j = tBatchItems.size() - 1; j >= 0; j--) {
                                        if ((tBatchItem1 = (IOTBatchItemInfo) tBatchItems.get(j)) != null) {
                                            boolean tExist = false;

                                            for (int k = aItems.size() - 1; k >= 0; k--) {
                                                if ((tBatchItem2 = aItems.get(k)) != null) {
                                                    if (tBatchItem1.iDevID == tBatchItem2.iDevID &&
                                                            tBatchItem1.iAddress == tBatchItem2.iAddress &&
                                                            tBatchItem1.iSize == tBatchItem2.iSize &&
                                                            Arrays.equals(tBatchItem1.iData, tBatchItem2.iData)) {
                                                        tExist = true;

                                                        break;
                                                    }
                                                }
                                            }

                                            if (tExist == false) {
                                                tSame = false;

                                                break;
                                            }
                                        } else {
                                            tSame = false;

                                            break;
                                        }
                                    }

                                    if (tSame) {
                                        tBatchs.add(tBatch);
                                    }
                                }
                            }
                        }
                    }

                    if (tBatchs.size() > 0) {
                        return tBatchs;
                    }
                }
            }
        }

        return null;
    }

    private IOTScanner<IOTBatch> iBatchScanner = new IOTScanner<IOTBatch>(this);

    @Override
    public boolean isScanning() {
        return iBatchScanner.isScanning();
    }

    @Override
    public boolean startScan(final IOTScanListener<IOTBatch> aScanListener) {
        if (isScanning() || !iNetAPI.isStarted()) {
            if (aScanListener != null) {
                aScanListener.onScanStop(null);
            }
            return false;
        }

        //根据数据版本判断数据是否有变化
        mTmpVersion = iNetAPI.getBatchVersion(0);

        //数据有变化则重新获取
        if (mTmpVersion != mLastVersion || iBatchs == null || iBatchs.size() <= 0) {
            final ListMap<Long, IOTBatch> tOldBatchs = iBatchs;
            final IOTBatchInfo tBatchInfo = new IOTBatchInfo();

            return iBatchScanner.startScan(new IOTScanner.ScanImpl<IOTBatch>() {

                int result = 0;

                /**
                 * 扫描开始
                 */
                @Override
                public void scanStart() {
                    if (iBatchs != null && iBatchs.size() > 0) {
                        iBatchs.clear();
                    } else {
                        iBatchs = new ListMap<Long, IOTBatch>();
                    }
                    BIArr.clear();
                }

                /**
                 * 根据扫描到的信息构建批处理条目
                 * @param aBatchInfo
                 * @return
                 */
                private IOTBatch buildBatch(IOTBatchInfo aBatchInfo) {
                    if (aBatchInfo != null) {
                        boolean tNew = true;
                        IOTBatch tBatch = null;

                        if (tOldBatchs != null) {
                            tBatch = tOldBatchs.getValue(aBatchInfo.getID());
                        }

                        if (tBatch == null) {
                            tBatch = new IOTBatch(aBatchInfo.getID(), aBatchInfo.getName());
                        } else {
                            tNew = false;

                            synchronized (tOldBatchs) {
                                tOldBatchs.remove(aBatchInfo.getID());
                            }

                            tBatch.setNameAndImgIndex(iBatchInterface, aBatchInfo.getName());
                        }

                        if (iBatchs.add(tBatchInfo.getID(), tBatch)) {
                            if (tNew) {
                                //设置监听
                                tBatch.setBatchInterfce(iBatchInterface);
                                //通知批处理列表的观察者
                                onNewObject(tBatch);
                            }

                            //==================================modify start============================
                            //获取添加到意向控制中的批处理
                            if (tBatch != null && tBatch.isAdd2Intention()) {
                                BIArr.add(new BatchIntentionDevice(tBatch));
                            }

                            if (mListChangeListener != null) {
                                mListChangeListener.onNewObject(null, tBatch);
                            }
                            //==================================modify end============================

                            return tBatch;
                        }
                    }

                    return null;
                }

                @Override
                public IOTBatch scanFirst() {
                    //记录扫描后的返回值
                    if ((result = iNetAPI.getBatchFirst(tBatchInfo)) == 0) {
                        IOTBatch batch = buildBatch(tBatchInfo);

                        return batch;
                    } else {
                        return null;
                    }
                }

                @Override
                public IOTBatch scanNext() {
                    //记录扫描后的返回值
                    if ((result = iNetAPI.getBatchNext(tBatchInfo)) == 0) {
                        IOTBatch batch = buildBatch(tBatchInfo);

                        return batch;
                    } else {
                        return null;
                    }
                }

                @Override
                public void scanDone() {
                    if (aScanListener != null) {
                        aScanListener.onScanStop(null);
                    }
                    if (tOldBatchs != null) {
                        for (int i = tOldBatchs.size() - 1; i >= 0; i--) {
                            onObjectRemoved(tOldBatchs.getValueAt(i));
                        }
                    }

                    //根据扫描后的返回值判断是否正常全部获取,而不是因为网络或其他原因中断
                    if (result == EIOT_RESULT.EIOT_RESULT_GENERAL_NO_BATCH) {
                        mLastVersion = mTmpVersion;
                    }

                }
            }, aScanListener);
        } else {
            //数据没有变化, 不用重新获取
            if (aScanListener != null) {
                aScanListener.onScanStop(null);
            }
            return true;
        }

    }

    @Override
    public boolean stopScan() {
        return iBatchScanner.stopScan();
    }

    public synchronized ArrayList<IOTBatchItemInfo> getAllBatchItemInfo(long aBatch) {
        if (aBatch != IOTNetAPI.KINVALID_BATCH_ID) {
            int tRet;
            int tCount = 0;
            IOTBatchItemInfo tItemInfo = new IOTBatchItemInfo();
            ArrayList<IOTBatchItemInfo> tList = new ArrayList<IOTBatchItemInfo>();

            do {
                if (tCount == 0) {
                    tRet = iNetAPI.getBatchItemFirst(aBatch, tItemInfo);
                } else {
                    tRet = iNetAPI.getBatchItemNext(aBatch, tItemInfo);
                }

                Log.e("getAllBatchItemInfo", "tItemInfo: " + tItemInfo.toString());

                if (tRet == 0) {
                    tCount++;
                    tList.add(tItemInfo.clone());
                }
            } while (tRet == 0);

            if (tList.size() > 0) {
                return tList;
            }
        }

        return null;
    }

    public synchronized IOTBatch addBatch(String aBatchName) {
        IOTLong tID = new IOTLong();

        if (iNetAPI.addBatch(aBatchName, tID)) {
            IOTBatch tBatch = new IOTBatch(tID.getValue(), aBatchName);
            tBatch.setBatchInterfce(iBatchInterface);
            super.onNewObject(tBatch);

            if (mListChangeListener != null) {
                mListChangeListener.onNewObject(null, tBatch);
            }

            startScan(null);

            return tBatch;
        }

        return null;
    }

    public synchronized boolean removeBatch(final IOTBatch aBatch) {
        final ListMap<Long, IOTBatch> tBatchs = iBatchs;

        if (aBatch != null) {
            if (iNetAPI.removeBatch(aBatch.getID())) {
                if (tBatchs != null) {
                    synchronized (tBatchs) {
                        tBatchs.remove(aBatch.getID());
                    }
                }

                super.onObjectRemoved(aBatch);

                if (mListChangeListener != null) {
                    mListChangeListener.onObjectRemoved(null, aBatch);
                }

                if (aBatch.isContainBlIr()) {
                    ThreadPoolUtils.getInstance().addTask(new Runnable() {
                        @Override
                        public void run() {
                            DBUtils.removeBatch(aBatch.getID());
                        }
                    });
                }
                startScan(null);
                return true;
            }
        }

        return false;
    }

    public boolean updateBatchIrCodes(IOTBatch aBatch, HashMap<String, ArrayList<CodeviewBean>> checkedIrCodes) {
        if (aBatch != null && aBatch.getID() != IOTNetAPIConst.KINVALID_BATCH_ID && checkedIrCodes != null && checkedIrCodes.size() > 0) {
            Set<String> strings = checkedIrCodes.keySet();
            ArrayList<CodeviewBean> allCodes = new ArrayList<>();
            for (String did : strings) {
                ArrayList<CodeviewBean> codes = checkedIrCodes.get(did);
                allCodes.addAll(codes);
            }

            if (allCodes.size() > 0) {
                DBUtils.removeBatch(aBatch.getID());
                DBUtils.addBatchItems(aBatch.getID(), allCodes);
            }
            return true;

        }
        return false;
    }

    /**
     * 更新情景模式的信息
     *
     * @param aBatch      情景模式model
     * @param aBatchItems 情景模式item的信息
     * @return
     */
    public boolean updateBatchItems(IOTBatch aBatch, ArrayList<IOTBatchItemInfo> aBatchItems) {
        if (aBatch != null && aBatch.getID() != IOTNetAPIConst.KINVALID_BATCH_ID && aBatchItems != null && aBatchItems.size() > 0) {
            ArrayList<IOTBatchItemInfo> tItems = getAllBatchItemInfo(aBatch.getID());

            if (tItems != null) {
                for (int i = 0; i < tItems.size(); i++) {
                    IOTBatchItemInfo iotBatchItemInfo = tItems.get(i);
                    LoggerUtil.i(Consts.BATCH, "data：" + iotBatchItemInfo.toString());

                }
            }


            if (tItems == null) {
                //New batch
                for (int i = 0, tCount = aBatchItems.size(); i < tCount; i++) {

                    if (iNetAPI.addBatchItem(aBatch.getID(), aBatchItems.get(i)) == false) {
                        return false;
                    }
                }

                return true;
            } else {
                //Edit batch
                IOTBatchItemInfo tItem1, tItem2;
                ArrayList<IOTBatchItemInfo> tNewItems = new ArrayList<IOTBatchItemInfo>();
                ArrayList<IOTBatchItemInfo> tOldItems = new ArrayList<IOTBatchItemInfo>();

                if (tItems.size() > 0) {
                    boolean tIsOld;

                    //Find the exist items
                    for (int i = aBatchItems.size() - 1; i >= 0; i--) {
                        tItem1 = aBatchItems.get(i);

                        if (tItem1 != null) {
                            tIsOld = false;

                            for (int j = tItems.size() - 1; j >= 0; j--) {
                                if ((tItem2 = tItems.get(j)) != null) {
                                    if (tItem1.iID == tItem2.iID) {
                                        tOldItems.add(tItem2);

                                        tItems.remove(j);

                                        tIsOld = true;

                                        break;
                                    }
                                } else {
                                    tItems.remove(j);
                                }
                            }

                            if (tIsOld == false) {
                                tNewItems.add(tItem1);
                            }
                        } else {
                            aBatchItems.remove(i);
                        }
                    }

                    //Replace the useless items
                    if (tNewItems.size() > 0) {
                        if (tItems.size() > 0) {
                            for (int i = tNewItems.size() - 1; i >= 0; i--) {
                                if (tItems.size() > 0) {
                                    tItem1 = tNewItems.get(i);
                                    tItem2 = tItems.get(0);

                                    tItem1.iID = tItem2.iID;

                                    tOldItems.add(tItem1);
                                    tNewItems.remove(i);
                                    tItems.remove(0);
                                } else {
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    tNewItems = aBatchItems;
                }

                //Delete the useless items
                if (tItems.size() > 0) {
                    for (int i = tItems.size() - 1; i >= 0; i--) {
                        if ((tItem1 = (IOTBatchItemInfo) tItems.get(i)) != null) {
                            if (iNetAPI.removeBatchItem(aBatch.getID(), tItem1.iID) == false) {
                                return false;
                            }
                        }
                    }
                }

                //Edit the exist items
                if (tOldItems != null) {
                    for (int i = tOldItems.size() - 1; i >= 0; i--) {
                        if (iNetAPI.editBatchItem(aBatch.getID(), tOldItems.get(i)) == false) {
                            return false;
                        }
                    }
                }

                //Add the new items
                if (tNewItems != null) {
                    for (int i = tNewItems.size() - 1; i >= 0; i--) {
                        if (iNetAPI.addBatchItem(aBatch.getID(), tNewItems.get(i)) == false) {
                            return false;
                        }
                    }
                }

                return true;
            }
        }

        return false;
    }

    private SequenceInvokeList<Long> iExecuteList = new SequenceInvokeList<Long>("Execute batch") {

        @Override
        public boolean onInvoke(Long aItem) {
            if (aItem != null) {
                //                int tRet = -1;
                boolean tScreenOn = ScreenMonitor.IsScreenOn();

                if (!tScreenOn && iWakeLock != null && iWakeLock.isHeld()) {
                    iWakeLock.acquire();
                }

                if (iNetAPI == null) {
                    IOTNetAPI.Initialize(MainManager.KDEFAULT_DATABASE_PATH, null);
                    iNetAPI = IOTNetAPI.GetInstance();
                }

                if (iNetAPI.executeBatch(aItem))/* == EIOT_RESULT.EIOT_RESULT_FATAL_USER_NOLOGIN)*/ {
                    //                    addInvalidTask(aItem);
                } /*else if (tRet == 0 && iWakeLock != null && iWakeLock.isHeld()) {
                    iWakeLock.release();
                }*/

                ArrayList<IrToBatchItemBean> irToBatchItemBeens = DBUtils.queryBatchItems(aItem);
                if (irToBatchItemBeens != null && irToBatchItemBeens.size() > 0) {
                    Connection dbConn = DBUtils.getDBConn();
                    HashMap<Long, String> disList = new HashMap<>();
                    for (IrToBatchItemBean bean : irToBatchItemBeens) {
                        String batchIrAirCode = DBUtils.getBatchIrAirCode(bean.codeId, dbConn);
                        String did = disList.get(bean.devID);
                        if (did == null) {
                            IOTBLDNADevice irDev = DBUtils.getIRDev(bean.devID, dbConn);
                            if (irDev != null) {
                                did = irDev.getDid();
                                disList.put(bean.devID, did);
                            }
                        }

                        if (did != null) {
                            String code = null;
                            if (bean.subDevID != 0 || !batchIrAirCode.startsWith("2600")) {
                                code = batchIrAirCode.substring(40);
                            } else {
                                code = batchIrAirCode;
                            }

                            SendIrTask.sendCodeByCode(did, code);
                        }

                    }
                    try {
                        dbConn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }

                if (iWakeLock != null && iWakeLock.isHeld()) {
                    iWakeLock.release();
                }
            }

            return true;
        }
    };

    private IOTBatchInterface iBatchInterface = new IOTBatchInterface() {
        @Override
        public boolean setName(IOTBatch aBatch, String aName) {
            if (aBatch != null) {
                return iNetAPI.editBatch(aBatch.getID(), aName);
            } else {
                return false;
            }
        }

        @Override
        public boolean execute(IOTBatch aBatch) {
            if (aBatch != null) {
                return executeBatch(aBatch.getID());
            }

            return false;
        }
    };

    public boolean executeBatch(long aBatch) {
        if (aBatch != IOTNetAPIConst.KINVALID_BATCH_ID && NetInfo.GetActiveNetwokInfo(App.GetInstance()) != null) {
            Debugger.Error("Execute batch " + aBatch);
            return iExecuteList.addItem(aBatch);
        }
        //        if (iNetAPI == null) {
        //            IOTNetAPI.Initialize(MainManager.KDEFAULT_DATABASE_PATH, null);
        //            iNetAPI = IOTNetAPI.GetInstance();
        //        }
        //        iNetAPI.startUp();
        //        addInvalidTask(aBatch);
        return false;
    }

    //======================modify start======================
    /**
     * 记录添加到意向控制中的batch的集合
     */
    private ArrayList<BatchIntentionDevice> BIArr = new ArrayList<BatchIntentionDevice>();

    public ArrayList<BatchIntentionDevice> getBIArr() {
        return BIArr;
    }

    public void addBIArrDev(BatchIntentionDevice dev) {
        if (!BIArr.contains(dev)) {
            BIArr.add(dev);
        }
    }

    public void removeBIArrDev(IOTBatch iotBatch){


        BatchIntentionDevice removeDevice = null;
        int size = BIArr.size();
        for (int i = 0; i < size; i++) {
            BatchIntentionDevice batchIntentionDevice = BIArr.get(i);
            IOTBatch batch = batchIntentionDevice.getBatch();
            if (batch == iotBatch){
                removeDevice = batchIntentionDevice;
                break;
            }
        }

        if (removeDevice != null && BIArr.contains(removeDevice)) {
            BIArr.remove(removeDevice);
        }
    }

    private IOTListChangeListener<IOTBatch> mListChangeListener = null;

    public void setOnListChangeListener(IOTListChangeListener<IOTBatch> listener) {
        if (mListChangeListener == null) {
            mListChangeListener = listener;
        }
    }

    private boolean addInvalidTask(long id) {
        FileOutputStream out = null;
        try {
            String data = UserManager.GetDefaultManager(getContext(), MainManager.KDEFAULT_DATABASE_PATH).getLogonUser() + "#" + id + "\n";
            out = getContext().openFileOutput(INVALID_TASK_NAME, Context.MODE_APPEND);
            out.write(data.getBytes());
            Log.e("writeTask", "Write: " + data);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //======================modify end======================


    public ArrayList<IOTBatch> getOfflineData(){
        if (iBatchs != null && iBatchs.size() > 0) {
            iBatchs.clear();
        } else {
            iBatchs = new ListMap<Long, IOTBatch>();
        }
        List<BatchBean> batchBeans = BatchDBManager.queryAllData();
        int size = batchBeans.size();

        for (int i = 0; i < size; i++) {
            try {
                BatchBean batchBean = batchBeans.get(i);
                IOTBatch iotBatch = new IOTBatch(batchBean.getBatchID(),batchBean.getNameAndImgIndex());
                String infoListJson = batchBean.getIotBatchItemInfoListJson();

                //GSON解析成对象
                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<IOTBatchItemInfoBean>>(){}.getType();
                List<IOTBatchItemInfoBean> itemInfoBeans = gson.fromJson(infoListJson, type);

                int infoBeanListSize = itemInfoBeans.size();

                ArrayList<IOTBatchItemInfo> iotBatchItemInfoList = new ArrayList<IOTBatchItemInfo>();
                //重新构建需要的对象
                for (int j = 0; j < infoBeanListSize; j++) {
                    IOTBatchItemInfoBean itemInfoBean = itemInfoBeans.get(j);
                    IOTBatchItemInfo iotBatchItemInfo = new IOTBatchItemInfo(itemInfoBean.getiID(),
                            itemInfoBean.getiDevID(),itemInfoBean.getiAddress(),itemInfoBean.getiSize(),itemInfoBean.getiData());
                    if (!iotBatchItemInfoList.contains(iotBatchItemInfo)){
                        iotBatchItemInfoList.add(iotBatchItemInfo);
                    }
                }

                iotBatch.setBatchItmeInfo(iotBatchItemInfoList);

                iotBatch.setOffLine(true);

                iBatchs.add(iotBatch.getID(),iotBatch);

            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        }
        return getList();
    }

}
